package com.android.videotest.music.ui.musiclist;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.RemoteException;
import android.support.v4.media.MediaBrowserCompat;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaControllerCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.videotest.R;
import com.android.videotest.base.BaseActivity;
import com.android.videotest.music.MusicService;
import com.android.videotest.music.ui.FilterPlayListActivity;
import com.android.videotest.music.ui.SimpleMusicActivity;
import com.android.videotest.music.ui.playlist.PlayListDialog;
import com.android.videotest.music.utils.Utils;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MusicListActivity extends BaseActivity implements MusicListAdapter.OnItemClickListener {
    @BindView(R.id.cardView)
    CardView cardView;

    public static void start(Context context) {
        Intent starter = new Intent(context, MusicListActivity.class);
        context.startActivity(starter);
    }

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.iv_image)
    ImageView ivImage;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_menu)
    ImageView ivMenu;
    @BindView(R.id.iv_playback_state)
    ImageView ivPlaybackState;
    @BindView(R.id.constraintLayout)
    ConstraintLayout constraintLayout;
    private MediaBrowserCompat mediaBrowser;
    private static final String TAG = "MediaPlayerActivity-App";
    private MusicListActivity mActivity;
    private MusicListAdapter mListAdapter;

    RecyclerView mRecyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = this;
        setContentView(R.layout.activity_music);
        ButterKnife.bind(this);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        mRecyclerView = findViewById(R.id.recyclerView);
        mListAdapter = new MusicListAdapter();
        mListAdapter.setOnItemClickListener(this);
        cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SimpleMusicActivity.start(mActivity);
            }
        });
        mRecyclerView.setAdapter(mListAdapter);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        // 创建MediaBrowserServiceCompat
        mediaBrowser = new MediaBrowserCompat(this, new ComponentName(this, MusicService.class),
                connectionCallbacks,
                null); // optional Bundle

    }

    @Override
    public void onStart() {
        super.onStart();
        mediaBrowser.connect();
    }

    @Override
    public void onResume() {
        super.onResume();
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (MediaControllerCompat.getMediaController(mActivity) != null) {
            MediaControllerCompat.getMediaController(mActivity).unregisterCallback(controllerCallback);
        }
        mediaBrowser.disconnect();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.play_list_menu, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.search) {
            FilterPlayListActivity.start(mContext);
        }
        return true;
    }
    /**
     * 连接成功的回调，连接成功后调用mediaBrowser.subscribe()来查找数据
     */
    private final MediaBrowserCompat.ConnectionCallback connectionCallbacks =
            new MediaBrowserCompat.ConnectionCallback() {
                @Override
                public void onConnected() {
                    Log.d(TAG, "onConnected() called");
                    try {
                        //获取MediaSession的令牌
                        MediaSessionCompat.Token token = mediaBrowser.getSessionToken();
                        // 创建一个MediaControllerCompat
                        MediaControllerCompat mediaController = new MediaControllerCompat(mActivity, token);
                        // 保存控制器
                        MediaControllerCompat.setMediaController(mActivity, mediaController);
                        // 完成构建UI
                        buildTransportControls();
                        mediaBrowser.unsubscribe(mediaBrowser.getRoot(), mediaBrowserSubscriptionCallback);
                        mediaBrowser.subscribe(mediaBrowser.getRoot(), mediaBrowserSubscriptionCallback);
                    } catch (RemoteException e) {

                    }
                }
            };

    /**
     * 构建传输控制界面
     */
    void buildTransportControls() {
        // 抓住视图的播放/暂停按钮
//        ImageView playPause = findViewById(R.id.play_pause);
//        // 将监听器附加到按钮
//        playPause.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                // 由于这是一个播放/暂停按钮，因此您需要测试当前状态并相应地选择操作
//                int pbState = MediaControllerCompat.getMediaController(mActivity).getPlaybackState().getState();
//                if (pbState == PlaybackStateCompat.STATE_PLAYING) {
//                    MediaControllerCompat.getMediaController(mActivity).getTransportControls().pause();
//                } else {
//                    MediaControllerCompat.getMediaController(mActivity).getTransportControls().play();
//                }
//            }
//        });
        ivMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PlayListDialog dialog = PlayListDialog.newInstance();
                dialog.show(getSupportFragmentManager(), "play_list_dialog");
            }
        });
        MediaControllerCompat mediaController = MediaControllerCompat.getMediaController(mActivity);
        MediaControllerCompat.TransportControls transportControls = mediaController.getTransportControls();
        transportControls.setRepeatMode(PlaybackStateCompat.REPEAT_MODE_ALL);
        transportControls.setShuffleMode(PlaybackStateCompat.SHUFFLE_MODE_ALL);

        ivPlaybackState.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PlaybackStateCompat playbackState = mediaController.getPlaybackState();
                if (playbackState.getState() == PlaybackStateCompat.STATE_PLAYING) {
                    transportControls.pause();
                } else {
                    transportControls.play();
                }
            }
        });

        // 显示初始状态
        MediaMetadataCompat metadata = mediaController.getMetadata();
        if (metadata != null) {
            String mediaId = metadata.getString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID);
            Log.d(this.getClass().getSimpleName() + "-App", "buildTransportControls: " + mediaId);
//        mRecyclerView.scrollToPosition();
        }
        Log.d(this.getClass().getSimpleName() + "-App", "buildTransportControls: ");
        updateUI(metadata);
        PlaybackStateCompat pbState = mediaController.getPlaybackState();
        updatePlaybackState(pbState);
        // 注册回调以保持同步
        mediaController.registerCallback(controllerCallback);
    }

    /**
     * 媒体浏览器订阅的回调，成功加载数据之后的回调，采用的是service那边的数据，以与service保持同步
     */
    MediaBrowserCompat.SubscriptionCallback mediaBrowserSubscriptionCallback = new MediaBrowserCompat.SubscriptionCallback() {
        @Override
        public void onChildrenLoaded(@NonNull String parentId, @NonNull List<MediaBrowserCompat.MediaItem> children) {
            String lastMediaId = Utils.getLastMusic(mContext);
            mListAdapter.setPlayingMediaId(lastMediaId);
            mListAdapter.setMediaItems(children);
            mRecyclerView.scrollToPosition(getPlayingViewPosition(children, lastMediaId));
        }
    };

    private int getPlayingViewPosition(@NonNull List<MediaBrowserCompat.MediaItem> children, String lastMediaId) {
        for (int i = 0; i < children.size(); i++) {
            String mediaId = children.get(i).getMediaId();
            if (mediaId != null && mediaId.equals(lastMediaId)) {
                return i;
            }
        }
        return -1;
    }

    /**
     * 控制器的回调，传递给MediaSession，播放数据或状态发生改变时调用
     */
    MediaControllerCompat.Callback controllerCallback = new MediaControllerCompat.Callback() {
        @Override
        public void onMetadataChanged(MediaMetadataCompat metadata) {
            updateUI(metadata);
            mListAdapter.setPlayingMediaId(metadata.getString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID));

        }

        @Override
        public void onPlaybackStateChanged(PlaybackStateCompat playbackState) {
            updatePlaybackState(playbackState);
        }
    };

    @Override
    public void onClick(MediaBrowserCompat.MediaItem item, int position) {
        Bundle extras = new Bundle();
        extras.putInt("position", position);
        MediaControllerCompat.getMediaController(mActivity).getTransportControls().playFromMediaId(item.getMediaId(), extras);
    }

    private void updatePlaybackState(PlaybackStateCompat playbackState) {
        if (playbackState != null) {
            if (playbackState.getState() == PlaybackStateCompat.STATE_PLAYING) {
                ivPlaybackState.setImageResource(R.drawable.ic_pause_tiny);
            } else {
                ivPlaybackState.setImageResource(R.drawable.ic_play_tiny);
            }
        }
    }

    private void updateUI(MediaMetadataCompat metadata) {
        if (metadata != null) {
            cardView.setVisibility(View.VISIBLE);
            CharSequence text = metadata.getText(MediaMetadataCompat.METADATA_KEY_TITLE);
            tvTitle.setText(text);
            ivImage.setImageBitmap(metadata.getBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART));
        } else {
            cardView.setVisibility(View.GONE);
        }
    }

}
